import os
import sys
import requests
import json
#Request URL: https://decipher.sanger.ac.uk/browser/API/CNV/Decipher.json?chr=20&start=61620196&end=62445768
#https://decipher.sanger.ac.uk/browser/API/CNV/Syndrome.json?chr=1&start=1&end=2250000
#https://decipher.sanger.ac.uk/data/syndromes

if len(sys.argv) != 2:
    print("\nUSAGE:   python {} <{}>".format(sys.argv[0],"outdir"))
    sys.exit()
#chrfile
##chr    start   end
#chr1    1       249250621

def ifNone(value):
    if (value == None or value == ''):
        value = '-'
        return value
    else:
        return value

def main(decipher,decipher_syndromes):
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400"}

    with open(decipher,'w') as dp:
        dp.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format('assembly','chr','start','end','id','project_id','user_id','patient_id','inheritance','pathogenicity','remap_value','remapped_from','grch37_position','mean_ratio'));
        with open(decipher_syndromes,'w') as ds:
            ##assembly       chr     start   end     id      copy_number     syndrome_id     short_description       grch37_position remap_value     remapped_from
            ds.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format('assembly','chr','start','end','id','copy_number','syndrome_id','short_description','grch37_position','remap_value','remapped_from','genotype','variant_class') )

            for oneChr in chrList_38:
                chr,start,end = oneChr

                #decipher
                link = "https://decipher.sanger.ac.uk/data/genome-browser/decipher-cnv?chr={}&start={}&end={}".format(chr,start,end)
                #link = "https://decipher.sanger.ac.uk/browser/API/CNV/Decipher.json?chr={}&start={}&end={}".format(chr_,start_,end_)

                try:
                    r = requests.get(link, headers=headers)
                    r.raise_for_status()
                    #print(r.status_code)
                    #print(r.content.decode('utf-8'))
                except requests.exceptions.InvalidURL:
                    print("invalid url error")
                except requests.exceptions.HTTPError:
                    r.raise_for_status()
                    print(" HTTP error")
                except:
                    print("something error")
                else:
                    data = json.loads(r.content.decode('utf-8'))
                    if (data):

                        out_info = ""
                        for element in data:
                            #print(element)
                            if element['alternative_positions']:

                                #assembly = ifNone(element.get('assembly', '-'))
                                assembly = ifNone(element['alternative_positions'][0].get('assembly', '-'))

                                #chrN = ifNone(element.get('chr', '-'))
                                chrN = ifNone(element['alternative_positions'][0].get('chr', '-'))

                                #start = ifNone(element.get('start', '-'))
                                start = ifNone(element['alternative_positions'][0].get('start', '-'))

                                #end = ifNone(element.get('end', '-'))
                                end = ifNone(element['alternative_positions'][0].get('end', '-'))

                           ###########################
                                idN = ifNone(element.get('id', '-'))
                                project_id = ifNone(element.get('project_id', '-'))
                                user_id = ifNone(element.get('user_id', '-'))
                                patient_id = ifNone(element.get('patient_id', '-'))
                                inheritance = ifNone(element.get('inheritance', '-'))
                                pathogenicity = ifNone(element.get('pathogenicity', '-'))
                                remap_value = ifNone(element.get('remap_value', '-'))
                                remapped_from = ifNone(element.get('remapped_from', '-'))
                                grch37_position = ifNone(element.get('original_position', '-'))
                                #mean_ratio = ifNone(element.get('variant_class', '-'))
                                mean_ratio = ifNone(element.get('mean_ratio', '-'))

                                out_info = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(assembly,
                                                                                                         chrN,
                                                                                                         start, end,
                                                                                                         idN,
                                                                                                         project_id,
                                                                                                         user_id,
                                                                                                         patient_id,
                                                                                                         inheritance,
                                                                                                         pathogenicity,
                                                                                                         remap_value,
                                                                                                         remapped_from,
                                                                                                         grch37_position,
                                                                                                         mean_ratio)

                            else:
                                continue

                            #print(out_info)
                            dp.write(out_info)
            #---------------------------------------------------------------------------------------------------------------
            #download decipher_syndrome
            #link_syndrome = "https://decipher.sanger.ac.uk/browser/API/CNV/Syndrome.json?chr={}&start={}&end={}".format(chr_,start_,end_)
            link_syndrome = "https://decipher.sanger.ac.uk/data/syndromes"

            try:
                r_syndrome = requests.get(link_syndrome, headers=headers)
                #print(r_syndrome.status_code)
                #print (r.encoding)
                #print(r.content.decode('utf-8'))
            except requests.exceptions.InvalidURL:
                print("invalid url error")
            except requests.exceptions.HTTPError:
                print("HTTP error")
            except:
                print("something error")
            else:
                data_syndrome = json.loads(r_syndrome.content.decode('utf-8'))
                if (data_syndrome):

                    new_dic = data_syndrome.get('content')
                    for syndrome_id in new_dic.keys():

                        # syndrome_id_syndrome = ifNone(element_syndrome.get('syndrome_id', '-'))
                        syndrome_id_syndrome = syndrome_id

                        #short_description_syndrome = ifNone(element_syndrome.get('short_description', '-'))
                        short_description_syndrome = new_dic[syndrome_id].get('name')
                        #print(short_description_syndrome)

                        for syndrome_variant_id in new_dic[syndrome_id]['Variants'].keys():

                           #idN_syndrome = ifNone(element_syndrome.get('id', '-'))
                           idN_syndrome = syndrome_variant_id
                           #print(idN_syndrome)

                           #variant_class_syndrome = ifNone(element_syndrome.get('variant_class', '-'))
                           variant_class_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id].get('variant_class','-'))

                           #copy_number_syndrome = ifNone(element_syndrome.get('copy_number', '-'))
                           copy_number_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id].get('copy_number','-'))

                           #genotype_syndrome = ifNone(element_syndrome.get('genotype', '-'))
                           genotype_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id].get('genotype','-'))

                           if (new_dic[syndrome_id]['Variants'][syndrome_variant_id]['alternative_positions']):
                               # assembly_syndrome = ifNone(element_syndrome.get('assembly', '-'))
                               assembly_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id]['alternative_positions'][0].get('assembly', '-'))

                               #chrN_syndrome = ifNone(element_syndrome.get('chr', '-'))
                               chrN_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id]['alternative_positions'][0].get('chr', '-'))

                               #start_syndrome = ifNone(element_syndrome.get('start', '-'))
                               start_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id]['alternative_positions'][0].get('start', '-'))

                               #end_syndrome = ifNone(element_syndrome.get('end', '-'))
                               end_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id]['alternative_positions'][0].get('end', '-'))

                               #remap_value_syndrome = ifNone(element_syndrome.get('remap_value', '-'))
                               remap_value_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id]['alternative_positions'][0].get('liftover_score', '-'))

                               #remapped_from_syndrome = ifNone(element_syndrome.get('remapped_from', '-'))
                               remapped_from_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id]['alternative_positions'][0].get('replaced_using', '-'))

                               #grch37_position_syndrome = ifNone(element_syndrome.get('original_position', '-'))
                               grch37_position_syndrome = ifNone(new_dic[syndrome_id]['Variants'][syndrome_variant_id]['alternative_positions'][0].get('original_position', '-'))

                               out_info_syndrome = "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(
                               assembly_syndrome, chrN_syndrome, start_syndrome, end_syndrome, idN_syndrome,
                               copy_number_syndrome, syndrome_id_syndrome, short_description_syndrome,
                               grch37_position_syndrome, remap_value_syndrome, remapped_from_syndrome,
                               genotype_syndrome, variant_class_syndrome)

                               ds.write(out_info_syndrome)
    dp.close()
    ds.close()
############################################################################################
#chrList = [[1,1,249250621],[2,1,243199373],[3,1,198022430],[4,1,191154276],[5,1,180915260],[6,1,171115067],[7,1,159138663],[8,1,146364022],[9,1,141213431],[10,1,135534747],[11,1,135006516],[12,1,133851895],[13,1,115169878],[14,1,107349540],[15,1,102531392],[16,1,90354753],
#[17,1,81195210],[18,1,78077248],[19,1,59128983],[20,1,63025520],[21,1,48129895],[22,1,51304566],['X',1,155270560],['Y',1,59373566],]
#
print("downloading decipher...waiting...")
#范围
chrList_38 = [[1,1,248956422],[2,1,242193529],[3,1,198295559],[4,1,190214555],[5,1,181538259],[6,1,170805979],[7,1,159345973],[8,1,145138636],[9,1,138394717],[10,1,133797422],
[11,1,135086622],[12,1,133275309],[13,1,114364328],[14,1,107043718],[15,1,101991189],[16,1,90338345],[17,1,83257441],[18,1,80373285],[19,1,58617616],[20,1,64444167],[21,1,46709983],[22,1,50818468],['X',1,156040895],['Y',1,57227415],['MT',1,16569],]

#
outDir = sys.argv[1];
file_cnv = os.path.join(outDir,"Decipher_CNV.all.txt")
file_syndrome = os.path.join(outDir,"Decipher_syndromes.all.txt")
#
main(file_cnv,file_syndrome)
